package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    //图片
    @Autowired
    private GraphInfoService graphInfoService;

    //公寓配套中间表（注意，一定是中间表！！！！！别把公寓配套删除了！！！！！！！！！！！）
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    //标签中间表（注意，一定是中间表！！！！！别把标签删除了！！！！！！！！！！！）
    @Autowired
    private ApartmentLabelService apartmentLabelService;

    //杂费值中间表（注意，一定是中间表！！！！！别把杂费值删除了！！！！！！！！！！！）
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private RoomInfoService roomInfoService;

    @Override
    public void queryPage(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        //返回值的page都是一个page
        apartmentInfoMapper.queryPage(page, queryVo);
    }





    @Autowired
    private ProvinceInfoMapper provinceInfoMapper;

    @Autowired
    private CityInfoMapper cityInfoMapper;

    @Autowired
    private DistrictInfoMapper districtInfoMapper;



    @Override
    public void customSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        //判断是否为更新还是保存（id为null是保存，id不为null是更新）
        boolean is = apartmentSubmitVo.getId() != null;

        //公寓信息保存或者更新(保存公寓信息，单表的数据)（调用的是父类中ServiceImpl的saveOrUpdate方法）
        saveOrUpdate(apartmentSubmitVo);

        //id为true是更新，id不为null是保存
        if (is) {
            //进行图片删除操作
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getId, apartmentSubmitVo.getId());
            //将类型写好，图片所属对象类型和ItemType.APARTMENT（表示公寓）保持一致
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            //删除
            graphInfoService.remove(graphInfoLambdaQueryWrapper);

            //进行配套删除
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

            //进行标签删除
            LambdaQueryWrapper<ApartmentLabel> labelInfoServiceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            labelInfoServiceLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId());
            apartmentLabelService.remove(labelInfoServiceLambdaQueryWrapper);

            //进行杂费值删除
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        }

        //进行数据插入保存

        //插入图片列表
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        //需要进行if判断（如果有数据就保存，没有数据就不保存）
        if(!CollectionUtils.isEmpty(graphVoList)){
            //指定一个长度，泛型为GraphInfo的实体类（不能直接用GraphVo！！！！）
            ArrayList<GraphInfo> graphInfosList = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                //图片的所属对象类型是：公寓 （不管有几张图片，当前操作都是公寓）
                graphInfo.setItemType(ItemType.APARTMENT);
                //图片所属对象id是：公寓ID （不管有几张图片，当前操作都是公寓ID）
                graphInfo.setItemId(apartmentSubmitVo.getId());
                //添加到graphInfosList中
                graphInfosList.add(graphInfo);
            }
            //saveBatch作用：批量保存
            graphInfoService.saveBatch(graphInfosList);
        }
        //插入公寓标签
        List<Long> LabelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(LabelIds)){
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>(LabelIds.size());
            for (Long LabelId : LabelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().labelId(LabelId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }
        //插入配套列表
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            //ApartmentFacility：公寓&配套关系
            ArrayList<ApartmentFacility> apartmentFacilities = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility build = ApartmentFacility.builder().facilityId(facilityInfoId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentFacilities.add(build);
            }
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }
        //插入杂费列表
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)){
            ArrayList<ApartmentFeeValue> apartmentFeeValues = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue build = ApartmentFeeValue.builder().feeValueId(feeValueId).apartmentId(apartmentSubmitVo.getId()).build();
                apartmentFeeValues.add(build);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }


        ProvinceInfo provinceInfo = provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId());
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());

        CityInfo cityInfo = cityInfoMapper.selectById(apartmentSubmitVo.getCityId());
        apartmentSubmitVo.setCityName(cityInfo.getName());


        DistrictInfo districtInfo = districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());
    }

    @Override
    public ApartmentDetailVo queryDetail(Long id) {
        //1. 根据id查询公寓的信息详情
        //service中特有的方法getById（mybatis-plus）
        //可能会查询不到，有可能管理员提前删掉了，页面不实时刷新，所以找不到，需要进行判断
        ApartmentInfo apartmentInfobyId = getById(id);
        if (apartmentInfobyId == null){
            return null;
        }
        //2. 根据公寓id查询配套详情
        //是一个多表查询，（推荐直接调用公寓配套的mapper，少了一层service方法）
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.queryByApartmentId(id);

        //3. 根据公寓id查询集合（图片表中存储公寓的图片但同时也存储房间的数据，想要复用性，根据房间的id可以查询对应的图片）
        //注意注意：使用的是GraphVo，不是GraphInfo！！！！！！ 具体看ApartmentDetailVo去！！！
        List<GraphVo> graphVoList = graphInfoMapper.queryById(id, ItemType.APARTMENT);

        //4. 根据公寓id查询标签集合
        List<LabelInfo> labelInfoList = labelInfoMapper.queryByApartmentId(id);

        //5. 根据公寓id查询杂费和杂费名集合（注意注意：：：是FeeValueVo）
        List<FeeValueVo> feeValueVoList = feeValueMapper.queryByApartmentId(id);

        //6. 合并到ApartmentDetailVo对象返回即可
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();

        //合体：
        // 炎龙铠甲合体，烈焰刀之封魔斩帖，斩邪除怪，熔于烈焰，消于晨曦
        apartmentDetailVo.setGraphVoList(graphVoList);

        // 风鹰铠甲合体，风鹰剑之穿风刺帖，降妖化兽，破于疾风，止于瞬间
        apartmentDetailVo.setLabelInfoList(labelInfoList);

        // 黑犀铠甲合体，流星枪之狂瀑扎帖，碎魔伏暴，灭于狂瀑，平如镜水
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);

        //地虎铠甲合体，裂地刀之裂地劈帖，劈狱驱暗，毁于怒土，复始大地
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        //帝皇铠甲合体。 炎龙侠、黑犀侠、雪獒侠、风鹰侠、地虎侠合体！
        //最后公寓的属性
        //将源对象的属性赋值给目标对象的相同属性，属性值迁移
        BeanUtils.copyProperties(apartmentInfobyId, apartmentDetailVo);

        return apartmentDetailVo;
    }

    @Override
    public void removeApartmentById(Long id) {
        //查询是否有公寓对应的房间
        LambdaQueryWrapper<RoomInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoomInfo::getApartmentId, id);
        //count：查询符合条件的总数量
        long count = roomInfoService.count(lambdaQueryWrapper);
        if (count > 0){
            //证明有对应的房间，不能删除，给与对应的状态码
            //两种方式结束，一种是return 一种是抛异常（异常处理流派来了！！！！！！！！！！！！！！！）
            //抛异常，不会正常返回结果（业务正确）使用全局异常处理器进行捕捉，进行返回对应的错误码给前端
            //自定义异常，默认的异常带不了抛出的错误（携带错误不同的状态码）
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        //删除公寓
        removeById(id);
        //删除公寓相关的配套
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

        //删除公寓相关的标签
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);

//        删除公寓相关的图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

//        删除公寓相关的杂费
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
    }
}




